// 预定义报表页面和我的分析页面
// 以url中的路径来划分
// 预定义报表：predefinedReport    我的分析：myAnalysis
import React from 'react';
import { RouteComponentProps } from 'react-router';
import { Row, Col, Space, Table, Input, Tooltip, Button, Popconfirm, message, Checkbox } from 'antd';
import { SearchOutlined, DeleteOutlined, PlusCircleOutlined, BarChartOutlined, PieChartOutlined, FontSizeOutlined } from '@ant-design/icons';
import styles from './index.module.scss';
import { connect } from 'react-redux';
import { getResourceIdByPath } from 'src/libs/utils';
import RenameModal from 'src/pages/AnalyseManage/Components/RenameModal';

import {
	getChildAnalysePageList,
	// delAnalysePage,
	batchDelAnalysePage,
	updateShareConfig,
	setHomePage,
	replaceDataSet,
} from 'src/services/AnalyseManage';
import { withRouter } from 'react-router-dom';
// import TreeNode from 'src/pages/AnalyseManage/PredefinedReport/components/TreeNode';
import BdhButton from 'src/pages/Components/BdhButton';
import ShareModal from './components/ShareModal';
import NewReportModal from 'src/pages/AnalyseManage/Components/NewReportModal';
import CopyModal from './components/CopyModal';
import { encryptParam } from 'src/libs/paramsEncrypt';
import { ReplaceDataSet } from '../MyAnalysis/components/ReplaceDataSet';

interface listItemType {
	name: string;
	id: string;
	effect: string;
	des: string;
	isFile: boolean;
}

interface RProps {
	match: {
		params: {
			id: string;
			isEdit: string;
		};
	};
	menu: any;
	user: any;
	btnAuth: any;
}
interface IProps {
	internalFlag: string;
	record: listItemType;
	handleEdit: ( item: listItemType, isEdit: boolean ) => void;
	handleDelete: ( item: listItemType ) => void;
	shareConfig: ( item: listItemType ) => void;
	handleRename: ( item: listItemType ) => void;
	handleCopy: ( item: listItemType ) => void;
	btnAuth: any;
}

//	操作栏组件
const OperateComponent = React.memo( ( props: IProps ) => {
	return props.btnAuth.includes( 'bi_deloitte_action' ) ? (
		<Space size="middle">
			<Tooltip placement="topRight" title="重命名">
				<Button
					type="text" icon={ <FontSizeOutlined className={ styles.green_btn }/> }
					onClick={ () => props.handleRename( props.record ) }></Button>
			</Tooltip>
			<Tooltip placement="topRight" title="查看">
				<Button
					type="text"
					icon={<span className={`iconfont bdhchakanxiangqing ${styles.green_btn}`}></span>}
					onClick={() => props.handleEdit( props.record, false )}
				></Button>
			</Tooltip>
			<Tooltip placement="topRight" title="克隆">
				<Button 
					type="text" 
					icon={<span className={`iconfont bdhxinzeng ${styles.green_btn}`}></span>}
					onClick={() => props.handleCopy( props.record )}
				></Button>
			</Tooltip>
			{
				props.internalFlag === '1' && (
					<>
						<Tooltip placement="topRight" title="权限">
							<Button
								type="text"
								icon={<span className={`iconfont bdhquanxian ${styles.green_btn}`}></span>}
								onClick={() => {
									props.shareConfig( props.record );
								}}
							></Button>
						</Tooltip>
						<Tooltip placement="topRight" title="编辑">
							<Button
								type="text"
								icon={<span className={`iconfont bdhxiugai ${styles.green_btn}`}></span>}
								onClick={() => props.handleEdit( props.record, true )}
							></Button>
						</Tooltip>
						<Tooltip placement="topRight" title="删除">
							<Popconfirm
								okText="确定"
								cancelText="取消"
								title="确定删除这一项？"
								placement="bottom"
								onConfirm={() => props.handleDelete( props.record )}
							>
								<Button type="text" icon={<span className={`iconfont bdhshanchu ${styles.green_btn}`}></span>}></Button>
							</Popconfirm>
						</Tooltip>
					</>
				)
			}
		</Space>
	) : (
		<Space size="middle">
			<Tooltip placement="topRight" title="查看">
				<Button
					type="text"
					icon={<span className={`iconfont bdhchakanxiangqing ${styles.green_btn}`}></span>}
					onClick={() => props.handleEdit( props.record, false )}
				></Button>
			</Tooltip>
		</Space>
	);
} );
OperateComponent.displayName = 'OperateComponent';

class PredefinedReport extends React.Component<RouteComponentProps & RProps> {


	state = {
		data: [], //	table数据
		treeData: [],
		activeTreeNode: '',
		keyword: '',
		resourceId: '',
		timer: null,
		tableLoading: false,
		page: 1,
		pageSize: 10,
		total: 0,
		pageConfigKey: '', //	当前页面是我的分析还是预定义报表，  我的分析: myAnalysis  预定义报表: predefinedReport
		pageConfig: {
			myAnalysis: {
				title: '我的分析',
			},
			predefinedReport: {
				title: '预定义报表',
			},
		},
		selectedRowKeys: [],
		shareModalVisible: false,
		shareConfigPageId: '',
		showDashboard: false,
		internalFlag: this.props.user.internalFlag,
		renameModalVisible: false,
		currentModalData: null,
		copyModalVisible: false,
		copyId: null,
		replaceModalShow: false,
	};

	//	列表表头配置
	columns = [
		{
			title: '报表名称',
			dataIndex: 'name',
			render: ( text, record ) => {
				let icon;
				if ( record.type === 'dashboard' ) {
					icon = <PieChartOutlined className={styles.green_btn} style={{ marginRight: '10px' }} />;
				} else if ( record.type === 'report' ) {
					icon = <BarChartOutlined className={styles.green_btn} style={{ marginRight: '10px' }} />;
				}
				return (
					<span className="bdh-link" onClick={() => this.handleEdit( record, false )}>
						{icon}{text}
					</span>
				);
			},
		},
		{
			title: '报表编码',
			dataIndex: 'code',
		},
		{
			title: '描述',
			dataIndex: 'des',
		},
		{
			title: '设为首页',
			dataIndex: 'homePage',
			align: 'center' as 'center',
			render: ( text, record ) => {
				const btnAuth = this.props.btnAuth;
				let checked = text === '1' ? true : false;
				if ( record.isFile ) return null;
				return (
					<>
						<Popconfirm
							disabled={ checked || !btnAuth.includes( 'bi_deloitte_action' ) }
							okText="确定"
							cancelText="取消"
							title="确定要设置为首页？"
							placement="top"
							onConfirm={ () => this.changeHomePage( true, record ) } >
							<Checkbox checked={ checked } disabled={ checked || !btnAuth.includes( 'bi_deloitte_action' ) } ></Checkbox>
						</Popconfirm>
					</>
				);
			},
		},
		{
			title: '操作',
			key: 'action',
			width: '300px',
			// eslint-disable-next-line react/display-name
			render: ( record: listItemType ) => (
				<OperateComponent
					record={record}
					handleCopy={this.handleCopy}
					handleEdit={ ( item, isEdit ) => this.handleEdit( item, isEdit ) }
					handleDelete={this.handleDelete}
					shareConfig={this.shareConfig}
					internalFlag={this.state.internalFlag}
					handleRename={ this.handleRename }
					btnAuth={ this.props.btnAuth }
				></OperateComponent>
			),
		},
	];

	// 设为主页
	changeHomePage = ( checked, row ) => {
		// console.log( checked, row );
		let oldData = JSON.parse( JSON.stringify( this.state.data ) );
		let data = JSON.parse( JSON.stringify( this.state.data ) );

		row.homePage = checked ? '1' : '0';
		data.forEach( ( item ) => {
			if ( item.id === row.id ) {
				item.homePage = row.homePage;
			} else if ( checked ) {
				item.homePage = '0';
			}
		} );
		this.setState( {
			data: [ ...data ],
		} );
		setHomePage( { data: row.id } )
			.then( ( res ) => {
				if ( res.data.success ) {
					message.success( '设置首页成功!' );
				} else {
					message.error( '设置首页失败!' );
					this.setState( {
						data: oldData,
					} );
				}
			} )
			.catch( ( err ) => {
				// message.error( '设置首页失败!' );
				this.setState( {
					data: oldData,
				} );
			} );
	};

	//	重命名
	handleRename = ( item: listItemType ) => {
		const modalData = {
			name: item.name,
			des: item.des,
			id: item.id,
			isFile: item.isFile
		};
		this.setState( {
			currentModalData: modalData,
			renameModalVisible: true
		} );
	};

	//	编辑
	handleEdit = ( item: listItemType, isEdit ) => {
		let editPath = '/analyseManage/editReport';
		let previewPath = '/analyseManage/previewReport';
		// this.props.history.push( { pathname: `${ isEdit ? editPath : previewPath }/${ item.id }/${ isEdit }` } );
		window.open(
			`${window.location.origin}${isEdit ? editPath : previewPath}/${encryptParam( item.id )}/${encryptParam( isEdit )}/${ encryptParam( isEdit ? 'EDIT' : 'PUBLISH' ) }`,
			'_blank'
		);
	};

	//	删除
	handleDelete = async ( item: listItemType ) => {
		const info = await batchDelAnalysePage( {
			type: 'PUBLISH',
			ids: [ item.id ], // this.state.selectedRowKeys,
		} );
		if ( info.data && info.data.success ) {
			message.success( '删除成功' );
			this.getList();
		}
	};

	shareConfig = ( item: listItemType ) => {
		this.setState( {
			shareModalVisible: true,
			shareConfigPageId: item.id,
		} );
	};

	updateShareConfig = async ( type, password ) => {
		const data = await updateShareConfig( {
			type,
			password,
			pageId: this.state.shareConfigPageId,
		} );

		if ( data.data.success ) {
			message.success( '修改成功' );
			this.hideModal();
		}
	};

	//	隐藏modal
	hideModal = () => {
		this.setState( {
			shareModalVisible: false,
			shareConfigPageId: '',
		} );
	};

	componentDidMount() {
		this.loadDatas();
	}

	componentDidUpdate( prevProps: Readonly<RouteComponentProps & RProps>, prevState: Readonly<{}>, snapshot?: any ): void {
		if ( prevProps.match.params.id !== this.props.match.params.id ) this.loadDatas();
		if ( prevProps.user.internalFlag !== this.props.user.internalFlag ) {
			this.setState( { internalFlag: this.props.user.internalFlag } );
		}
		//更新resourceId
		if ( prevProps.menu.length !== this.props.menu.length ) {
			this.loadDatas();
		}
	}

	loadDatas = async () => {
		const resource = getResourceIdByPath( this.props.menu, this.props.location.pathname );
		if( resource ) {
			this.setState(
				{
					showDashboard: false,
					resourceId: resource.resourceId
				},
				() => {
					this.clickNode( resource.resourceId );
				}
			);
		}
	};

	clickNode = ( id: string ) => {
		this.setState(
			{
				activeTreeNode: id,
				tableLoading: true,
			},
			() => {
				this.getList();
			}
		);
	};

	getList = async () => {
		let response = await getChildAnalysePageList( {
			categoryId: this.state.activeTreeNode,
			name: this.state.keyword,
			page: this.state.page,
			size: this.state.pageSize,
		} );
		if ( response.data && response.data.success ) {
			let dates = response.data.data.rows;
			this.setState( { data: dates } );
		}

		this.setState( {
			tableLoading: false,
		} );
	};

	//	切换页码
	handlePageChange = ( pageNumber: number ) => {
		this.setState(
			{
				page: pageNumber,
			},
			() => {
				this.getList();
			}
		);
	};

	//	修改每页数量
	setPageSize = ( size: number ) => {
		this.setState( {
			pageSize: size,
		} );
	};

	//	输入框搜索
	handleSearchInput = ( e ) => {
		e.persist();

		let value = e.target.value;
		this.setState( {
			keyword: value,
		} );

		if ( this.state.timer ) clearTimeout( this.state.timer );
		let timer = setTimeout( () => {
			this.getList();
		}, 300 );
		this.setState( {
			timer: timer,
		} );
	};

	// 批量删除
	handleBatchDel = async () => {
		let response = await batchDelAnalysePage( {
			ids: this.state.selectedRowKeys,
			type: 'EDIT'
		} );
		if ( response.data && response.data.success ) {
			message.success( '删除成功' );
			this.getList();
			this.setState( {
				selectedRowKeys: [],
			} );
		}
	};

	handleSelectionChange = ( selectedRowKeys ) => {
		this.setState( { selectedRowKeys } );
	};

	// 新建仪表板
	onSuccess = ( id: string ) => {
		this.setState( { showDashboard: false } );
		this.props.history.push( { pathname: `/analyseManage/editReport/${encryptParam( id )}/${encryptParam( 'true' )}/${encryptParam( 'EDIT' )}` } );
	};

	onToggleDashboard = () => {
		let value = !this.state.showDashboard;
		this.setState( { showDashboard: value } );
	};

	toggleRenameModalVisible = ( isVisible: boolean, isLoadData: boolean = false ) => {
		this.setState( { renameModalVisible: isVisible } );
		if( isLoadData ) this.getList();
	};

	handleCopy = ( item: listItemType ) => {
		console.log( item );
		this.setState( {
			copyModalVisible: true,
			copyId: item.id,
			currentModalData: item
		} );
	}

	onCopySuccess = ( ) => {
		this.setState( { replaceModalShow: true } );
	}

	handleReplace = async( arr ) => {
		const data = {
			pageId: this.state.currentModalData.id,
			replaceItemDtoList: arr
		};
		const res = await replaceDataSet( data );
		if ( res.data && res.data.success ) {
			message.success( '替换成功' );
			this.setState( { replaceModalShow: false } );
		}
	};

	render() {
		const btnAuth = this.props.btnAuth;
		return (
			<>
				<div className={styles.report_contanier}>

					<div className={styles.table_container}>
						<Row justify="space-between">
							<Col span={12} style={{ textAlign: 'left' }}>
								{
									this.state.internalFlag === '1' && (
										<>
											{
												btnAuth.includes( 'bi_deloitte_addDashBoard' ) && (
													<BdhButton
														align="horizontal"
														label="新建仪表板"
														className="primary-transpanent"
														onClick={() => {
															this.onToggleDashboard();
														}}
														icon={ <PlusCircleOutlined className={ styles.greenBtn }/> }
													></BdhButton>
												)
											}
											{
												btnAuth.includes( 'bi_deloitte_batchDel' ) && (
													<Popconfirm
														okText="确定"
														cancelText="取消"
														title="确定删除选中数据？"
														placement="bottom"
														onConfirm={this.handleBatchDel}
													>
														<BdhButton
															align="horizontal"
															label="批量删除"
															className="grey-transpanent"
															onClick={null}
															icon={<DeleteOutlined />}
														></BdhButton>
													</Popconfirm>
												)
											}
										</>
									)
								}
							</Col>
							<Col xs={24} sm={6} md={6} lg={6} xl={6} style={{ textAlign: 'right' }}>
								<Input placeholder="请输入报表名称回车搜索" allowClear onChange={this.handleSearchInput} prefix={<SearchOutlined />} />
							</Col>
						</Row>

						<Table
							loading={this.state.tableLoading}
							rowSelection={{ type: 'checkbox', onChange: this.handleSelectionChange }}
							scroll={{ x: '100%' }}
							tableLayout="fixed"
							columns={this.columns}
							dataSource={this.state.data}
							className={styles.table}
							bordered={true}
							rowKey={( row: listItemType ) => row.id}
							size="middle"
							pagination={{
								showSizeChanger: true,
								pageSize: this.state.pageSize,
								total: this.state.total,
								onChange: this.handlePageChange,
								onShowSizeChange: ( current, size ) => this.setPageSize( size ),
								showTotal: ( total ) => `共 ${total} 条`,
							}}
						/>
					</div>

					{this.state.shareConfigPageId && (
						<ShareModal
							pageId={this.state.shareConfigPageId}
							shareModalVisible={this.state.shareModalVisible}
							handleOk={this.updateShareConfig}
							handleCancel={this.hideModal}
						></ShareModal>
					)}
				</div>
				{this.state.showDashboard && (
					<NewReportModal
						modalVisible={this.state.showDashboard}
						name="仪表板"
						pageType="dashboard"
						deloitteFlag="1"
						parentTreeId={ this.state.resourceId}
						onSuccess={( id ) => this.onSuccess( id )}
						onCancel={() => {
							this.onToggleDashboard();
						}}
					></NewReportModal>
				)}
				{ this.state.replaceModalShow && (
					<ReplaceDataSet
						currentModalData={this.state.currentModalData}
						modalVisible={this.state.replaceModalShow}
						handleReplace={this.handleReplace}
						closeModal={() => this.setState( { replaceModalShow: false } )}></ReplaceDataSet>
				)}
				{this.state.copyModalVisible && 
				<CopyModal
					 pageId={this.state.copyId}
				 	 modalVisible={this.state.copyModalVisible}
					 onSuccess={this.onCopySuccess}
					 onCancel={() => {
						this.setState( { copyModalVisible: false } );
					 }}></CopyModal>}
				<RenameModal
					modalVisible={this.state.renameModalVisible}
					toggleVisible={this.toggleRenameModalVisible}
					currentModalData={this.state.currentModalData}></RenameModal>
			</>
		);
	}
}

//	映射state到当前组件
const mapStateToProps = ( state ) => {
	return {
		menu: state.menu,
		user: state.user,
		btnAuth: state.btnAuth,
	};
};


//	映射dispatch到当前组件
// const mapDispatchToProps = ( dispatch ) => {
// 	return {
// 		// getResourceId: ( path ) => {
// 		// 	dispatch( getResourceId( path ) );
// 		// }
// 	};
// };

export default connect(
	mapStateToProps,
	// mapDispatchToProps
)( withRouter( PredefinedReport ) );
